package com.white.interfaceone.util;

import com.github.pagehelper.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @version v1.0
 * @ProjectName: interfaceone
 * @ClassName: ImgToBase64Utils
 * @Description: TODO(一句话描述该类的功能)
 * @Author: sunbo@pgytesting.cn
 * @Date: 2019/5/6 10:36
 */
public class ImgBase64Utils {


    private static final Logger LOG = LoggerFactory.getLogger(ImgBase64Utils.class);


    /**
     * @param @param imgFile 图片本地路径
     * @return @return base64字符串
     * @throws
     * @Title: ImageToBase64ByLocal
     * @Description: TODO(本地图片转换成base64字符串)
     * @author sunbo@pgytesting.cn
     * @date 2019/5/6 10:44
     */
    public static String ImageToBase64ByLocal(String imgFile) {

        InputStream in;
        byte[] data = null;


        LOG.info("读取图片");
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }

        LOG.info("对字节数组base64编码");
        BASE64Encoder encoder = new BASE64Encoder();

        LOG.info("返回Base64编码过的字节数组字符串");
        return encoder.encode(data);

    }


    /**
     * @param @param imgURL 图片线上路径
     * @return @return base64字符串
     * @throws
     * @Title: ImageToBase64ByOnline
     * @Description: TODO(在线图片转换成base64字符串)
     * @author sunbo@pgytesting.cn
     * @date 2019/5/6 10:53
     */
    public static String ImageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();

        try {
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            LOG.info("创建http连接");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            LOG.info("讲内容读取到内存中");
            int len;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            LOG.info("关闭输入流");
            is.close();

        } catch (IOException e) {
            LOG.error("线图片转换成base64字符串错误");
        }

        LOG.info("对字节数组Base64编码");
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());

    }


    /**
     * @Title: Base64ToImage
     * @Description: TODO(base64字符串转换成图片)
     * @param imgStr base64字符串，
     * @param imgFilePath 图片存放路径
     * @return 是否成功
     * @author sunbo@pgytesting.cn
     * @throws
     * @date 2019/5/6 11:05
     */
    public static boolean Base64ToImage(String imgStr, String imgFilePath) {
        LOG.info("对字节数组字符串进行Base64解码并生成图片");
        if (StringUtil.isEmpty(imgStr)) {
            LOG.info("图像数据为空");
            return false;
        }


        BASE64Decoder decoder = new BASE64Decoder();
        try {
            LOG.info("进行base64转换字节");
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; i++) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            LOG.info("进行图片文件写入");
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);

            LOG.info("写入完成进行缓存刷新");
            out.flush();

            LOG.info("关闭输出流");
            out.close();
            return true;
        } catch (Exception e) {
            LOG.error("base64转换图片文件失败");
            return false;
        }
    }



    // 测试类
    public static void main(String[] args) {
        String url = "C:/Users/frosty/Pictures/微信图片_20190424170514.jpg";

        String string = "http://bpic.588ku.com//element_origin_min_pic/17/03/03/7bf4480888f35addcf2ce942701c728a.jpg";

        String str = ImgBase64Utils.ImageToBase64ByLocal("C:/Users/frosty/Pictures/扫描/扫描_20190220.png");
//        String ste = ImgBase64Utils.ImageToBase64ByOnline(string);
        System.out.println(str);
//        ImgBase64Utils.Base64ToImage(str,"C:/Users/frosty/Desktop/test1.jpg");
//        ImgBase64Utils.Base64ToImage(ste, "C:/Users/frosty/Desktop/test2.jpg");


        // 模拟请求
//        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
//        HashMap<String, String> map = new HashMap<>();
//        HashMap<String, byte[]> byteMap = new HashMap<>();
//        map.put("api_key", "你的KEY");
//        map.put("api_secret", "你的SECRET");
//        map.put("return_landmark", "1");
//        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
//        byteMap.put("image_base64", str);
    }
}
